using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public interface IBagItemView
{
    void Setup(BagItemData data, EventMode mode);
    void Refresh();
    bool IsHighlighted { get; set; }
    BagItemData BagItemData { get; set; }
}


public abstract class BagItemData
{
    public string Title { get; set; }
    public abstract string Path { get; }
}
public enum EventMode
{
    Default,
    Custom
}

public enum LayoutDirection
{
    Vertical,   // 竖直排列，列数不限
    Horizontal, // 水平排列，行数不限
    Grid        // 网格布局，每行固定列数
}

public class BagContent : MonoBehaviour
{
    [Header("类型配置")]
    [SerializeField] private string tView;
    [SerializeField] private string tData;

    [Header("引用配置")]
    [SerializeField] private Transform contentParent;

    [Header("布局配置")]
    [SerializeField] private LayoutDirection layoutDirection = LayoutDirection.Vertical;
    [SerializeField] private float stepX = 5f;
    [SerializeField] private float stepY = 5f;

    [Header("Grid 布局设置")]
    [SerializeField, Min(1)]
    private int gridColumns = 3; // Inspector 设置每行列数，只在 Grid 布局下有效

    [Header("元素缩放设置")]
    [SerializeField] private Vector3 elementScale = Vector3.one; // 在 Inspector 调整每个元素的缩放
    public Vector3 ElementScale => elementScale;

#if UNITY_EDITOR
    private void OnValidate()
    {
        if (layoutDirection != LayoutDirection.Grid)
        {
            gridColumns = Mathf.Max(gridColumns, 1);
        }
    }
#endif

    private List<BagItemData> dataList = new List<BagItemData>();
    private List<IBagItemView> viewList = new List<IBagItemView>();
    private List<List<BagItemData>> data2D = new List<List<BagItemData>>();
    private EventMode mode= EventMode.Custom;

    private Type tViewType;
    private Type tType;

    public Transform ContentParent => contentParent;
    public float StepX => stepX;
    public float StepY => stepY;
    public LayoutDirection Layout => layoutDirection;

    private void Awake() => ParseTypes();

    private void ParseTypes()
    {
        if (string.IsNullOrEmpty(tView)) { Debug.LogError("请在 Inspector 设置 tView"); return; }
        tViewType = Type.GetType(tView);
        if (tViewType == null) { Debug.LogError($"找不到视图类型 {tView}"); return; }
        if (!typeof(IBagItemView).IsAssignableFrom(tViewType)) { Debug.LogError($"{tView} 没有实现 IBagItemView"); return; }

        if (string.IsNullOrEmpty(tData)) { Debug.LogError("请在 Inspector 设置 tData"); return; }
        tType = Type.GetType(tData);
        if (tType == null) { Debug.LogError($"找不到数据类型 {tData}"); return; }

        Debug.Log($"类型解析成功：TView={tViewType.Name}, TData={tType.Name}");
    }

    #region Setup / Refresh

    public void Setup(List<BagItemData> newDataList)
    {
        if (newDataList == null || newDataList.Count == 0) { ClearViews(); return; }

        if (layoutDirection == LayoutDirection.Grid)
        {
            // Grid 布局按列数拆成二维列表
            List<List<BagItemData>> twoDimData = new List<List<BagItemData>>();
            int total = newDataList.Count;
            int rows = Mathf.CeilToInt((float)total / gridColumns);

            for (int r = 0; r < rows; r++)
            {
                List<BagItemData> rowList = new List<BagItemData>();
                for (int c = 0; c < gridColumns; c++)
                {
                    int index = r * gridColumns + c;
                    if (index < total) rowList.Add(newDataList[index]);
                }
                twoDimData.Add(rowList);
            }
            Setup(twoDimData);
        }
        else
        {
            Setup(new List<List<BagItemData>> { newDataList });
        }
    }

    public void Setup(List<List<BagItemData>> newDatas2D)
    {
        if (newDatas2D == null || newDatas2D.Count == 0) { ClearViews(); return; }

        data2D = newDatas2D;
        dataList.Clear();
        ClearViews();

        foreach (var subList in data2D)
        {
            if (subList == null) continue;
            foreach (var data in subList)
            {
                if (data == null) continue;
                IBagItemView view = BagItemViewCreator.Instance.CreateView(data, contentParent,mode);
                if (view != null)
                {
                    // 设置缩放
                    if (view is MonoBehaviour mono)
                        mono.transform.localScale = elementScale;

                    viewList.Add(view);
                    dataList.Add(data);
                }
            }
        }

        Arrange(layoutDirection, stepX, stepY);
    }

    public void Refresh() { foreach (var view in viewList) view.Refresh(); }

    #endregion

    #region View 管理

    public void ClearViews()
    {
        foreach (var view in viewList)
            if (view is MonoBehaviour mono)
                Destroy(mono.gameObject);
        viewList.Clear();
    }

    public List<IBagItemView> GetViews() => viewList;
    public List<BagItemData> GetData() => dataList;

    #endregion

    #region 布局

    public void Arrange(LayoutDirection direction, float stepX, float stepY)
    {
        if (viewList.Count == 0 || data2D.Count == 0) return;

        if (direction == LayoutDirection.Grid)
        {
            int columns = Mathf.Max(1, gridColumns);
            for (int i = 0; i < viewList.Count; i++)
            {
                if (viewList[i] is MonoBehaviour mono)
                {
                    int row = i / columns;
                    int col = i % columns;
                    mono.transform.localPosition = new Vector3(col * stepX, -row * stepY, 0);
                }
            }
            return;
        }

        int viewIndex = 0;
        for (int i = 0; i < data2D.Count; i++)
        {
            var subList = data2D[i];
            if (subList == null) continue;

            for (int j = 0; j < subList.Count; j++)
            {
                if (viewIndex >= viewList.Count) break;
                if (viewList[viewIndex] is MonoBehaviour mono)
                {
                    if (direction == LayoutDirection.Vertical)
                        mono.transform.localPosition = new Vector3(i * stepX, -j * stepY, 0);
                    else
                        mono.transform.localPosition = new Vector3(j * stepX, -i * stepY, 0);
                }
                viewIndex++;
            }
        }
    }

    #endregion

    #region 行列信息（供滚动条使用）

    public int GetTotalRows()
    {
        if (layoutDirection == LayoutDirection.Vertical)
        {
            int maxRows = 0;
            foreach (var col in data2D)
                if (col != null) maxRows = Mathf.Max(maxRows, col.Count);
            return maxRows;
        }
        else if (layoutDirection == LayoutDirection.Grid)
        {
            int totalRows = Mathf.CeilToInt((float)viewList.Count / gridColumns);
            return totalRows;
        }
        else return data2D.Count;
    }

    public int GetTotalColumns()
    {
        if (layoutDirection == LayoutDirection.Vertical) return data2D.Count;
        else if (layoutDirection == LayoutDirection.Grid) return gridColumns;
        else
        {
            int maxCols = 0;
            foreach (var row in data2D)
                if (row != null) maxCols = Mathf.Max(maxCols, row.Count);
            return maxCols;
        }
    }

    #endregion
}
